const { app, BrowserWindow, screen, dialog } = require('electron')


const getWH = () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize
  let h = height
  let w = parseInt(h * 1.333984375)
  let b = 1
  while (w > width) {
    b -= 0.1
    h = parseInt(height * b)
    w = parseInt(height * 1.333984375)
  }
  return { w, h }
}

const createWindow = () => {

  // 创建加载窗口，显示加载动画或效果
  let loadingWindow = new BrowserWindow({
    width: 400,
    height: 250,
    frame: false,
    // transparent: true,
    alwaysOnTop: true
  });

  // 在加载窗口中加载本地的 HTML 文件，该文件显示加载动画或效果
  loadingWindow.loadFile('index.html');


  const { w, h } = getWH()
  const win = new BrowserWindow({
    width: w,
    height: h,
    fullscreen: false,
    show: false
    // frame: false
  })
  let beforWinWidth = w
  let beforWinHeight = h

  // 监听失败加载事件
  win.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
    console.log(`加载失败: ${errorDescription}`);
    // 隐藏加载窗口并显示错误消息
    if (loadingWindow) {
      loadingWindow.close();
      loadingWindow = null
    }
    if (win) {
      win.close();
    }
    // 使用对话框模块展示全局弹窗
    dialog.showErrorBox('fail to load', `${errorDescription}`);
  });

  // 监听框架完成加载事件
  win.webContents.on('did-frame-finish-load', (event, isMainFrame) => {
    if (isMainFrame) {
      if (loadingWindow) {
        loadingWindow.close();
        loadingWindow = null
      }
      console.log('主框架加载完成');
      win.show()
    } else {
      console.log('子框架加载完成');
    }
  });

  win.loadURL(`https://app.bigread.ai?t=${Date.now()}`);
  win.on('resize', () => {
    const [_width, _height] = win.getSize()
    let newWidth = _width
    let newHeight = _height
    if (_height !== beforWinHeight) {
      newWidth = parseInt(_height * 1.333984375)
    } else if (_width !== beforWinWidth) {
      newHeight = parseInt(_width / 1.333984375)
    } else
      beforWinWidth = newWidth
    beforWinHeight = newHeight
    win.setSize(newWidth, newHeight)
  })
}

app.whenReady().then(() => {
  createWindow()
})